<?php

/**
 * 家族
 */

namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use think\facade\Db;

class FamilyController extends AdminbaseController
{
	
	protected function getState($k = '')
	{
		$status = array(
			'0' => '未审核',
			'1' => '审核失败',
			'2' => '审核通过',
		);
		if($k === ''){
			return $status;
		}
		
		return $status[$k] ?? '';
	}
	
	protected function getState2($k = '')
	{
		$status = array(
			'0' => '未处理',
			'1' => '提现成功',
			'2' => '拒绝提现',
		);
		if($k === ''){
			return $status;
		}
		
		return $status[$k] ?? '';
	}
	
	function index()
	{
		$data = $this->request->param();
		$map  = [];
		//家族收益查询条件
		$profit_map = [];
		$map[]      = ['state', '<>', 3];
		
		$start_time = $data['start_time'] ?? '';
		$end_time   = $data['end_time'] ?? '';
		
		if($start_time != ""){
			$map[] = ['addtime', '>=', strtotime($start_time)];
		}
		
		if($end_time != ""){
			$map[] = ['addtime', '<=', strtotime($end_time) + 60 * 60 * 24];
		}
		//家族收益统计
		$profit_start_time = $data['profit_start_time'] ?? '';
		$profit_end_time   = $data['profit_end_time'] ?? '';
		if($profit_start_time != ""){
			$profit_map[] = ['addtime', '>=', strtotime($profit_start_time)];
		}
		if($profit_end_time != ""){
			$profit_map[] = ['addtime', '<=', strtotime($profit_end_time) + 60 * 60 * 24];
		}
		
		$state = $data['state'] ?? '';
		if($state != ''){
			$map[] = ['state', '=', $state];
		}
		
		$uid = $data['uid'] ?? '';
		if($uid != ''){
			$lianguid = getLianguser($uid);
			if($lianguid){
				//$map[]=['uid',['=',$uid],['in',$lianguid],'or'];
				array_push($lianguid, $uid);
				$map[] = ['uid', 'in', $lianguid];
			} else{
				$map[] = ['uid', '=', $uid];
			}
		}
		
		$keyword = $data['keyword'] ?? '';
		if($keyword != ''){
			$map[] = ['name', 'like', '%'.$keyword.'%'];
		}
		
		$lists = Db::name("family")
				   ->where($map)
				   ->order("addtime DESC")
				   ->paginate(20);
		
		$lists->each(function($v, $k) use ($profit_map) {
			$v['userinfo'] = getUserInfo($v['uid']);
			$v['badge']    = get_upload_path($v['badge']);
			//统计对应的收益数据
			$profit_map[]       = ['familyid', '=', $v['id']];
			$profit             = Db::name("family_profit")->where($profit_map)->sum("profit");
			$v['profit']        = $profit ?? 0;
			$profit_anthor      = Db::name("family_profit")->where($profit_map)->sum("profit_anthor");
			$v['profit_anthor'] = $profit_anthor ?? 0;
			$total              = Db::name("family_profit")->where($profit_map)->sum("total");
			$v['total']         = $total ?? 0;
			
			return $v;
		});
		
		$lists->appends($data);
		$page = $lists->render();
		
		$this->assign('lists', $lists);
		$this->assign("page", $page);
		$this->assign("state", $this->getState());
		
		return $this->fetch();
	}
	
	function disable()
	{
		$id = $this->request->param('id', 0, 'intval');
		
		$rs = DB::name('family')->where("id={$id}")->update(['disable' => 1]);
		if($rs === false){
			$this->error("禁用失败！");
		}
		
		$action = "禁用家族：{$id}";
		setAdminLog($action);
		
		$this->success("禁用成功！");
		
	}
	
	function enable()
	{
		$id = $this->request->param('id', 0, 'intval');
		
		$rs = DB::name('family')->where("id={$id}")->update(['disable' => 0]);
		if($rs === false){
			$this->error("启用失败！");
		}
		
		$action = "启用家族：{$id}";
		setAdminLog($action);
		
		$this->success("启用成功！");
		
	}
	
	function del()
	{
		$id = $this->request->param('id', 0, 'intval');
		
		$rs = DB::name('family')->where("id={$id}")->update(['state' => 3]);
		if($rs === false){
			$this->error("删除失败！");
		}
		
		DB::name("family_profit")->where(["familyid" => $id])->delete();
		
		$data = array(
			'state'         => 3,
			'signout'       => 2,
			'signout_istip' => 2,
		);
		DB::name("family_user")->where(["familyid" => $id])->update($data);
		
		$action = "删除家族：{$id}";
		setAdminLog($action);
		
		$this->success("删除成功！");
		
	}
	
	// 影票
	function profit()
	{
		$data = $this->request->param();
		$uid  = $this->request->param('uid', 0, 'intval');
		$map  = [];
		
		$start_time = $data['start_time'] ?? '';
		$end_time   = $data['end_time'] ?? '';
		$anchor_uid = $data['anchor_uid'] ?? '';
		$rwhere     = [];
		$s_time     = 0;
		$e_time     = 0;
		if($start_time != ""){
			$s_time   = strtotime($start_time);
			$map[]    = ['addtime', '>=', $s_time];
			$rwhere[] = ['endtime', '>=', $s_time];
		}
		if($end_time != ""){
			$e_time   = strtotime($end_time) + 60 * 60 * 24;
			$map[]    = ['addtime', '<=', $e_time];
			$rwhere[] = ['starttime', '<=', $e_time];
		}
		if($anchor_uid != ''){
			$map[] = ['uid', '=', $anchor_uid];
		}
		
		$ufamilyinfo = DB::name("family_user")->where(["uid" => $uid])->find();
		if($ufamilyinfo){
			$map[] = ['uid', '=', $uid];
		} else{
			$familyinfo = DB::name("family")->where(["uid" => $uid])->find();
			$map[]      = ['familyid', '=', $familyinfo['id']];
		}
		
		// 查询
		$lists = Db::name("family_profit")->where($map)->order("id DESC")->paginate(20);
		
		// 直播记录：统计在线时长
		$lives = [];
		$uids  = $lists->column('uid');
		if($uids){
			$record = Db::name("live_record")->where('uid', 'in', $uids)->where($rwhere)->select()->toArray();
			foreach($record as $_live){
				$_endtime   = $e_time > 0 ? ($_live['endtime'] > $e_time ? $e_time : $_live['endtime']) : $_live['endtime'];
				$_starttime = $_live['starttime'] > $s_time ? $_live['starttime'] : $s_time;
				// 组合  $s_time
				$lives[$_live['uid']] = ($lives[$_live['uid']] ?? 0) + $_endtime - $_starttime;
			}
		}
		// 整理
		$lists->each(function($v, $k) use ($lives) {
			$v['userinfo'] = getUserInfo($v['uid']);
			
			//$v['in_live']  = round(($lives[$v['uid']] ?? 0) / 60, 2);
			
			return $v;
		});
		// 整理直播
		$inlives = [];
		foreach($lives as $_uid => $_time){
			$inlives[] = ['uid' => $_uid, 'time' => $this->timeToDate($_time), 'user' => getUserInfo($_uid),];
		}
		
		$lists->appends($data);
		$page = $lists->render();
		
		
		$total_family = Db::name("family_profit")->where($map)->sum("profit");
		if(!$total_family){
			$total_family = 0;
		}
		$total_anthor = Db::name("family_profit")->where($map)->sum("profit_anthor");
		if(!$total_anthor){
			$total_anthor = 0;
		}
		$total = Db::name("family_profit")->where($map)->sum("total");
		if(!$total){
			$total = 0;
		}
		
		$this->assign('total_family', $total_family);
		$this->assign('total_anthor', $total_anthor);
		$this->assign('total', $total);
		$this->assign('uid', $uid);
		$this->assign('lists', $lists);
		$this->assign('inlives', $inlives);
		$this->assign("page", $page);
		
		return $this->fetch();
	}
	
	// 影票导出
	public function profit_explode()
	{
		$data = $this->request->param();
		$uid  = $this->request->param('uid', 0, 'intval');
		$map  = [];
		
		$xlxTitle   = '';
		$cloTitle   = '';
		$rwhere     = [];  // 计算直播里面的映票条件
		$gwhere     = [];  // 计算直播游戏投注的条件
		$start_time = $data['start_time'] ?? '';
		$end_time   = $data['end_time'] ?? '';
		$anchor_uid = $data['anchor_uid'] ?? '';
		$s_time     = 0;
		$e_time     = 0;
		if($start_time != ""){
			$s_time   = strtotime($start_time);
			$map[]    = ['addtime', '>=', $s_time];
			$rwhere[] = ['endtime', '>=', $s_time];
			$gwhere[] = ['addtime', '>=', $s_time];
			// Excel文件名
			$xlxTitle .= '从'.$start_time;
			$cloTitle .= $start_time;
		}
		if($end_time != ""){
			$e_time   = strtotime($end_time) + 60 * 60 * 24;
			$map[]    = ['addtime', '<=', $e_time];
			$rwhere[] = ['endtime', '<=', $e_time];
			$gwhere[] = ['addtime', '<=', $e_time];
			// Excel文件名
			$xlxTitle .= '到'.$end_time;
			$cloTitle .= '-'.$end_time;
		}
		if($anchor_uid != ''){
			$map[] = ['uid', '=', $anchor_uid];
			// Excel文件名
			$xlxTitle .= '主播ID'.$anchor_uid;
		}
		
		// 获取用户所在的家族id
		$ufamilyinfo = DB::name("family_user")->where(["uid" => $uid])->find();
		if($ufamilyinfo){
			$map[] = ['uid', '=', $uid];
		} else{
			$familyinfo = DB::name("family")->where(["uid" => $uid])->find();
			$map[]      = ['familyid', '=', $familyinfo['id']];
		}
		
		// 查询家族收益
		$lists = Db::name("family_profit")->where($map)->order("id DESC")->select()->toArray();
		
		
		// 直播记录：统计在线时长
		// 游戏记录：投注金额
		$lives  = [];
		$bets   = [];
		$uids   = array_column($lists, 'uid');
		$today  = strtotime(date("Y-m-d"));
		$yesday = $today - 86400;
		$thrday = $yesday - 86400;
		if($uids){
			// 直播记录：统计在线时长
			$record = Db::name("live_record")->where('uid', 'in', $uids)->where($rwhere)->select()->toArray();
			foreach($record as $_live){
				// 根据搜索时间与开始时间和结束时间对比，计算直播时长
				// 搜索时间以外的不计入时长
				//$_endtime   = $e_time > 0 ? ($_live['endtime'] > $e_time ? $e_time : $_live['endtime']) : $_live['endtime'];
				//$_starttime = $_live['starttime'] > $s_time ? $_live['starttime'] : $s_time;
				// 组合  $s_time
				//$lives[$_live['uid']]['times'] = ($lives[$_live['uid']]['times'] ?? 0) + $_endtime - $_starttime;
				
				// 直接根据开播时间与结束时间计算直播时长
				// 与搜索的时间无关
				$lives[$_live['uid']]['times'] = ($lives[$_live['uid']]['times'] ?? 0) + $_live['endtime'] - $_live['starttime'];
				$lives[$_live['uid']]['votes'] = ($lives[$_live['uid']]['votes'] ?? 0) + $_live['votes'];
			}
			
			// 获取用户直播时候的各个位置的投注映票
			$action   = 1;  // 炸金花游戏
			$grecords = Db::name("gamerecord")->where('liveuid', 'in', $uids)->where('action', '=', $action)->where($gwhere)->order("id DESC")->select()->toArray();
			foreach($grecords as $_bet){
				$bets[$_bet['liveuid']]['votes'] = ($bets[$_bet['liveuid']]['votes'] ?? 0) + $_bet['coin_1'] + $_bet['coin_2'] + $_bet['coin_3'] + $_bet['coin_4'] + $_bet['coin_5'] + $_bet['coin_6'];
			}
			
			// 导出前两天的直播的影票数据
			/*$twhere[] = [['starttime', '>=', $thrday], ['starttime', '<=', $yesday]];
			$ywhere[] = [['starttime', '>=', $yesday], ['starttime', '<=', $today]];
			$trecord  = Db::name("live_record")->where('uid', 'in', $uids)->field('uid,sum(votes) number')->where($twhere)->group('uid')->select()->toArray();
			$yrecord  = Db::name("live_record")->where('uid', 'in', $uids)->field('uid,sum(votes) number')->where($ywhere)->group('uid')->select()->toArray();
			$trecord  = array_column($trecord, 'number', 'uid');
			$yrecord  = array_column($yrecord, 'number', 'uid');*/
		}
		
		// 整理
		$result = [];
		foreach($lists as $item){
			$item['userinfo']     = getUserInfo($item['uid']);
			$result[$item['uid']] = [
				'uid'           => $item['uid'],
				'nickname'      => $item['userinfo']['user_nickname'],
				'in_live1'      => $lives[$item['uid']]['times'] ?? 0,
				'in_live2'      => $this->timeToDate($lives[$item['uid']]['times'] ?? 0),
				'profit_anthor' => $item['profit_anthor'] + ($result[$item['uid']]['profit_anthor'] ?? 0),
				'profit'        => $item['profit'] + ($result[$item['uid']]['profit'] ?? 0),
				'total'         => $item['total'] + ($result[$item['uid']]['total'] ?? 0),
				'yesday'        => $lives[$item['uid']]['votes'] ?? 0,
				'bet'           => $bets[$item['uid']]['votes'] ?? 0,
				//'yesday'        => $yrecord[$item['uid']] ?? 0,
				//'thrday'        => $trecord[$item['uid']] ?? 0,
			];
		}
		
		//表头
		$headList = [
			'uid'           => '会员ID',
			'nickname'      => '用户昵称',
			'in_live1'      => '直播时长（秒）',   // 根据直播结算的（与直播有关）
			'in_live2'      => '直播时长（分）',   // 根据直播结算的（与直播有关）
			'profit_anthor' => '主播映票',   // 是每一笔操作产生记录统计的
			'profit'        => '家族映票',   // 是每一笔操作产生记录统计的
			'total'         => '总映票',     // 是每一笔操作产生记录统计的
			'yesday'        => $cloTitle.'直播映票',  // 根据直播结算的（与直播有关）
			'bet'           => '游戏映票流水',         // 是投注相关的，不知道用来干嘛的
			//'yesday'        => date('Y-m-d', $yesday).'直播映票',
			//'thrday'        => date('Y-m-d', $thrday),
		];
		
		array_unshift($result, $headList);
		$headTitle = "合作单位 优惠券赠送记录";
		$title     = "合作单位记录";
		$xlxTitle  .= "映票汇总";
		$headTitle = $xlxTitle;
		$headtitle = "<tr style='height:50px;border-style:none;'><th border=\"0\" style='height:60px;font-size:26px;' colspan='".count($headList)."' >{$headTitle}</th></tr>";
		$headtitle = "<tr style='height:40px;'><th border=\"0\" style='height:40px;font-size:26px;' colspan='".count($headList)."' >{$headTitle}</th></tr>";
		$filename  = $xlxTitle.".xls";
		
		$str = $this->excelData($result, $headtitle, $filename);
		exit($str);
	}
	
	// 时间处理
	protected function timeToDate($time)
	{
		$days  = floor($time / (24 * 3600));
		$time  = $time - $days * 24 * 3600;
		$hours = floor($time / 3600);
		$time  = $time - $hours * 3600;
		$mins  = floor($time / 60);
		$socs  = $time - $mins * 60;
		
		return ($days ? $days.'天' : '').($hours ? $hours.'时' : '').($mins ? $mins.'分' : '').($socs ? $socs.'秒' : '');
	}
	
	/*
	*处理Excel导出
	*@param $datas array 设置表格数据
	*@param $titlename string 设置head
	*@param $title string 设置表头
	*/
	protected function excelData($datas, $title, $filename)
	{
		$str = "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\nxmlns:x=\"urn:schemas-microsoft-com:office:excel\"\r\nxmlns=\"http://www.w3.org/TR/REC-html40\">\r\n<head>\r\n<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">\r\n</head>\r\n<body>";
		$str .= "<style>tr,td,th{text-align: center;height: 26px;line-height: 26px;}td{min-width: 250px;}</style>";
		$str .= "<table border=1>";
		$str .= $title;
		foreach($datas as $key => $rt){
			$str .= "<tr>";
			foreach($rt as $k => $v){
				$str .= "<td>{$v}</td>";
			}
			$str .= "</tr>\n";
		}
		$str .= "</table></body></html>";
		header("Content-Type: application/vnd.ms-excel; name='excel'");
		header("Content-type: application/octet-stream");
		header("Content-Disposition: attachment; filename=".$filename);
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Pragma: no-cache");
		header("Expires: 0");
		
		return $str;
	}
	
	function cash()
	{
		$data = $this->request->param();
		$uid  = $this->request->param('uid', 0, 'intval');
		
		$map   = [];
		$map[] = ['uid', '=', $uid];
		
		$ufamilyinfo = DB::name("family_user")->where(["uid" => $uid])->find();
		if($ufamilyinfo){
			$map[] = ['addtime', '>', $ufamilyinfo['addtime']];
		}
		
		$lists = Db::name("cash_record")
				   ->where($map)
				   ->order("id DESC")
				   ->paginate(20);
		$lists->each(function($v, $k) {
			$v['userinfo'] = getUserInfo($v['uid']);
			
			return $v;
		});
		
		$lists->appends($data);
		$page = $lists->render();
		
		$total = Db::name("cash_record")->where('status=1')->where($map)->sum("money");
		if(!$total){
			$total = 0;
		}
		$this->assign('total', $total);
		$this->assign("state", $this->getState2());
		$this->assign('lists', $lists);
		$this->assign("page", $page);
		
		return $this->fetch();
		
	}
	
	function edit()
	{
		$id   = $this->request->param('id', 0, 'intval');
		$data = Db::name('family')
				  ->where("id={$id}")
				  ->find();
		if(!$data){
			$this->error("信息错误");
		}
		
		$data['userinfo'] = getUserInfo($data['uid']);
		$this->assign('data', $data);
		$this->assign("state", $this->getState());
		
		return $this->fetch();
		
	}
	
	function editPost()
	{
		if($this->request->isPost()){
			$data = $this->request->param();
			
			$data['istip'] = 1;
			
			$rs = DB::name('family')->update($data);
			if($rs === false){
				$this->error("修改失败！");
			}
			
			$action = "修改家族信息：{$data['id']}";
			setAdminLog($action);
			$this->success("修改成功！");
			
		}
	}
	
	
}